$(function(){
	
	var commonUrl = '/course-work-management/teacher';
	var savedScores =[];
	
	// Tooltip
	$('[data-tooltip="true"]').tooltip();
	
	// Load course and its teacher works for the first time
	initCoursesAndTeacherWorks();
	
	// Reset form after hidding the modal
	$('.modal').on('hidden.bs.modal', function() {
        if($(this).find('form')) {
            $(this).find('form')[0].reset();
        }
        
        if($(this).find('.alert')) {
        	$(this).find('.alert').alert('close');
        }
    });
	
	// Show a modal and add a new course
	$('#addCourseModal button:last').on('click', function(){
		if ($('#addCourseModal input').val().length == 0) {
			$('#addCourseModal .modal-body').prepend(createAlert('danger', 'Error', '课程名称不为空！'));
		} else {
			var param = {
					courseName : $('#addCourseModal input').val(),
					courseNo : $('#addCourseModal option:selected').text()
			};
			$.post(commonUrl + '/course/action/add', param, function(result){
				if(result.succeeded){
					$('#addCourseModal').modal('hide');
					initCoursesAndTeacherWorks();
				} else {
					$('#addCourseModal .modal-body').prepend(createAlert('danger', 'Error', result.message));
				}
			});
		}
	});
	
	// Delete course and alert message
	$('#deleteCourseModal button:last').on('click', function(){
		$.ajax({
			url: commonUrl + '/course/id/' + $('#courses select option:selected').val(),
			type: 'DELETE',
		}).done(function(result){
			$('#deleteCourseModal').modal('hide');
			if(result.succeeded){
				initCoursesAndTeacherWorks();
			} else {
				$('.container:eq(1)').prepend(createAlert('danger', 'Error', result.message));
			}
		});
	});
	
	// Change course option and get teacher works of this course
	$('#courses select').on('change', function(){
		// Reset teacher work and student works panel
		resetWorkPanel();
		loadTeacherWorksData($('#courses select option:selected').val())
	});
	
	// change the file's name when selecting file
	$('#addTeacherWorkModal input[type="file"]').on('change', function(e) {
        var filename = $(e.currentTarget).val().replace(/^.*\\/, "");
        $('#addTeacherWorkModal input[type="text"]:eq(1)').val(filename);
    });

	// Show a modal and add a new teacher work
    $('#addTeacherWorkModal .modal-footer button:last').on('click', function() {
        var inputItems = $('#addTeacherWorkModal input[type="text"]');
        if (inputItems[0].value.length == 0 || $('#addTeacherWorkModal textarea').val().length == 0 ||
        		inputItems[2].value.length == 0 || inputItems[3].value.length == 0) {
        	$('#addTeacherWorkModal .modal-body').prepend(createAlert('danger', 'Error', '标题，内容，期限不为空！'));
        } else {
        	var formData = new FormData();
            formData.append('title', inputItems[0].value);
            formData.append('content', $('#addTeacherWorkModal textarea').val());
            formData.append('attachment', $('#addTeacherWorkModal input[type="file"]')[0].files[0]);
            formData.append('deadline', inputItems[2].value + ' ' + inputItems[3].value);
            formData.append('courseId', $('#courses select option:selected').val());
            $.ajax({
            	url: commonUrl + '/teacher-work/action/add',
            	type: 'POST',
            	data: formData,
            	contentType: false,
            	cache: false,
            	processData: false
            }).done(function(result) {
            	if(result.succeeded) {
            		$('#addTeacherWorkModal').modal('hide');
            		loadTeacherWorksData($('#courses select option:selected').val());
            	} else {
            		$('#addTeacherWorkModal .modal-body').prepend(createAlert('danger', 'Error', result.message));
            	}
            });
        }
    }); 
    
    // Show a modal and delete teacher work
    $('#deleteTeacherWorkModal .modal-footer button:last').on('click', function() {
    	$.ajax({
    		url: commonUrl + '/teacher-work/id/' + $('#workPanelHeading').data('id'),
    		type: 'DELETE'
    	}).done(function(result) {
    		$('#deleteTeacherWorkModal').modal('hide');
    		if(result.succeeded) {
    			resetWorkPanel();
    			loadTeacherWorksData($('#courses select option:selected').val());
    		} else {
    			$('.container:eq(1)').prepend(createAlert('danger', 'Error', result.message));
    		}
    	});
    });
    
    
    // Update scores of student work 
    $('#workPanelHeading button:eq(0)').on('click', function() {
    	var formData = new FormData();
		var count = 0;
    	$('#tabContentStudentWork table tr[class="success"]').each(function(index) {
    		if($(this).find('input').val() != savedScores[index].score) {
    			formData.append('ids', savedScores[index].id);
    			formData.append('scores', $(this).find('input').val());
    			count ++;
    		}
    	});
    	if(count > 0) {
			$.ajax({
				url : commonUrl + '/student-works/action/update',
				type: 'POST',
	        	data: formData,
	        	contentType: false,
	        	cache: false,
	        	processData: false
			}).done(function(result) {
				if(result.succeeded) {
    				$('.container:eq(1)').prepend(createAlert('success', 'Success', 'Update successful.'));
    			} else {
    				$('.container:eq(1)').prepend(createAlert('danger', 'Error', result.message));
    			}
			});
		} else {
			$('.container:eq(1)').prepend(createAlert('info', 'Note', "成绩尚未更新."));
		}
    });
	
	// Refresh course data
	function loadCoursesData() {
		return $.get(commonUrl + '/courses', function(data){
				   $('#courses select').empty();
				   $.each(data, function(index){
					   $('#courses select').append('<option value="' + data[index].id + '">' + data[index].courseName + '_' + data[index].courseNo +'</option>');
				   });
			   });
	}
	
	// Refresh teacher works data
	function loadTeacherWorksData(courseId) {
		var teacherWorksDiv = $("#teacherWorks .list-group div");
		$.get(commonUrl + '/course/id/' + courseId + '/teacher-works', function(data){
			teacherWorksDiv.empty();
			$.each(data, function(index){
				teacherWorksDiv.append('<a href="" class="list-group-item" style="margin-bottom: 5px;" data-id="' + data[index].id + '">' + data[index].title + '</a>');
			});
		}).done(function(){
			if(teacherWorksDiv.find('a')) {
				teacherWorksDiv.find('a').on('click', function(e){
				   	e.preventDefault();
				   	loadCurrentTeacherWorkAndStudentWorksData($(e.target).data('id'));
				});
			}
		});
	}
	
	// Refresh current teacher work detail data and current student works
	function loadCurrentTeacherWorkAndStudentWorksData(teacherWorkId){
		// Get teacher work
		$.get(commonUrl + '/teacher-work/id/' + teacherWorkId, function(data){
    		$('#workPanelHeading li:eq(0)').text($('#courses select option:selected').text());
    		$('#workPanelHeading li:eq(1)').text(data.title);
    		$('#workPanelHeading').data('id', teacherWorkId);
    		$('#workPanelHeading button').each(function() {
    			$(this).show();
    		});
    		$('#tabContentTeacherWork table').html(
				'<tbody>' + 
					'<tr><th class="col-md-2">标题:</th>' + '<th class="col-md-10">' + data.title + '</th></tr>' +
					'<tr><th>内容:</th>' + '<th><pre style="max-width: 570px; overflow: auto;">' + data.content + '</pre></th></tr>' +
					'<tr><th>发布日期:</th>' + '<th>' + getFormattedTime(data.informDate) + '</th></tr>' +
					'<tr><th>提交期限:</th>' + '<th>' +getFormattedTime(data.deadline) + '</th></tr>' +
					'<tr><th>附件:</th>' + '<th><a href="' + commonUrl + '/teacher-work/id/' + data.id + '/attachment">' + getFileName(data.filePath) + '</a></th></tr>' +
				'</tbody>'
    		);
    	});
    	// Get student works
    	$.get(commonUrl + '/teacher-work/id/' + teacherWorkId + '/student-works', function(data){
    		$('#tabContentStudentWork table tbody').empty();
    		savedScores = [];
    		$.each(data, function(index){
    			if(data[index].submitted) {
    				$('#tabContentStudentWork table tbody').append(
	    				'<tr class="success">' +
	    					'<td>' + data[index].student.no + '</td>' +
	    					'<td>' + data[index].student.name + '</td>' + 
	    					'<td>' + getFormattedTime(data[index].submitDate) + '</td>' +
	    					'<td>' +
	    						'<a href="' + commonUrl + '/student-work/id/' + data[index].id + '/attachment">' + getFileName(data[index].filePath) + '</a>' +
	    					'</td>' + 
	    					'<td>' + 
	    						'<input type="number" class="form-control" value="' + data[index].score + '">' +
	    					'</td>' +
	    				'</tr>'
    	    		);
    				
    				// Save ids and scores of the current student work.
    				savedScores.push({
    					id : data[index].id,
    					score : data[index].score
    				});
    			} else {
    				$('#tabContentStudentWork table tbody').append(
	    				'<tr class="danger">' +
	    					'<td>' + data[index].student.no + '</td>' +
	    					'<td>' + data[index].student.name + '</td>' + 
	    					'<td></td>' +
	    					'<td></td>' + 
	    					'<td></td>' +
	    				'</tr>'
        	    	);
    			}
    		});
    	});
	}
	
	function initCoursesAndTeacherWorks() {
		loadCoursesData().done(function(){
			if($('#courses select').find('option')) {
				loadTeacherWorksData($('#courses select:first-child').val());
			}
		});
	}
	
	// Reset teacher work and student works panel
	function resetWorkPanel() {
		$('#workPanelHeading li').each(function() {
			$(this).text('');
		});
		$('#workPanelHeading').data('id', '');
		$('#workPanelHeading button').each(function() {
			$(this).hide();
		});
		$('#tabContentTeacherWork table').empty();
		$('#tabContentStudentWork table tbody').empty();
	}
	
	// Format time
	function getFormattedTime(time) {
		if(time) {
			var date = new Date();
			date.setTime(time);
			return date.format('yyyy-mm-dd  HH:mm:ss');
		} else {
			return '';
		}
	}
	
	// get file name from file path
	function getFileName(filePath) {
		if(filePath) {
			return String(filePath).substring(filePath.lastIndexOf("/") + 1);
		} else {
			return '';
		}
	}
	
	// Make alert
	function createAlert(status, tip, message) {
		return '<div class="alert alert-' + status + '"><a href="#" class="close" data-dismiss="alert">&times;</a><strong>' + tip + '! </strong>' + message + '</div>'
	}
});